/**
 * 
 */
package com.bs.resa.shiro;


import javax.annotation.Resource;

import com.bs.resa.common.JedisUtils;
import com.bs.resa.common.RedisUtils;
import com.bs.resa.common.StringUtils;
import com.bs.resa.pojo.AdminUser;
import com.bs.resa.service.AdminUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 自定义realm
 *
 * @Author lin
 * @date 2019/3/16 22:55
 */
@Component
public class MyShiroRealm extends AuthorizingRealm {
    private static Logger logger= LoggerFactory.getLogger(MyShiroRealm.class);
	@Resource
	AdminUserService adminUserService;
	@Resource
	RedisUtils redisUtils;
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	/**
	 * 授权Realm
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("授权");
		//获得用户id
		String account = (String)principals.getPrimaryPrincipal();

		Long userid = adminUserService.findByUserAccount(account).getId();
//		Long userid=((AdminUser)redisUtils.getObject("userinfo")).getId();
		System.out.println("用户id:"+userid);
		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		/**根据用户ID查询角色（role），放入到Authorization里.*/
		info.setRoles(adminUserService.findRoleByUserId(userid));

		if (info != null && info.getStringPermissions() != null) {
			Set<String> permissions = info.getStringPermissions();
			for (String permission : permissions) {
				if (StringUtils.isEmpty(permission)) {
					permissions.remove(permission);
				}
			}
		}

		/**根据用户ID查询权限（permission），放入到Authorization里.*/
		info.setStringPermissions(adminUserService.findPermissionByUserId(userid));
		return info;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	/**
	 * 登录认证Realm
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		String username = (String)token.getPrincipal();
		logger.info("认证");
		String password = new String((char[])token.getCredentials());
		logger.info("[username:"+username+",password:"+password+"]");
		AdminUser user = adminUserService.login(username, password);
		logger.info("user:"+user.toString());
		redisUtils.setObject("userinfo",user);
		if(null==user){
			throw new AccountException("帐号或密码不正确！");
		}
		if(user.getIsDisabled()){
			throw new DisabledAccountException("帐号已经禁止登录！");
		}
//		**密码加盐**交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
		return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),ByteSource.Util.bytes("3.14159"), getName());
//		return null;
	}

	
    /**
     * 清空当前用户权限信息
     */
	public  void clearCachedAuthorizationInfo() {
		PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principalCollection, getName());
		super.clearCachedAuthorizationInfo(principals);
	}
	/**
	 * 指定principalCollection 清除
	 */
	public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principalCollection, getName());
		super.clearCachedAuthorizationInfo(principals);
	}
	
	
}
